package com.chinawayltd.ews.sample.service.materiel.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinawayltd.ews.sample.mapper.TLogMapper;
import com.chinawayltd.ews.sample.mapper.TMaterielMapper;
import com.chinawayltd.ews.sample.mapper.material.MaterielExtendMapper;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TMateriel;
import com.chinawayltd.ews.sample.model.TMaterielExample;
import com.chinawayltd.ews.sample.model.materiel.MaterielVO;
import com.chinawayltd.ews.sample.service.base.impl.BaseServiceImpl;
import com.chinawayltd.ews.sample.service.materiel.MaterielService;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExportCloumsModel;
import com.chinawayltd.ews.sample.web.query.MaterielGirdQuery;

/**
 * @program: greeProject
 * @description
 * @author: chenxin
 * @create: 2018年4月16日 下午3:39:13
 */
@Service
public class MaterielServiceImpl extends BaseServiceImpl implements MaterielService {

	@Autowired
	private MaterielExtendMapper materielExtendMapper;
	@Autowired
	private TMaterielMapper tMaterielMapper;
	@Autowired
	private TLogMapper tLogMapper;

	private final String tableName = "T_MATERIEL";

	@Override
	public List<MaterielVO> listMaterielByPage(MaterielGirdQuery queryParam) throws Exception{
		return materielExtendMapper.listMaterielByPage(queryParam);
	}

	@Override
	public TMateriel getMaterielById(Long id) throws Exception{
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		return tMaterielMapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional
	public int insertMateriel(TMateriel tMateriel) throws Exception{
		tMateriel.setCreateTime(new Date());
		tMateriel.setCreateTime(new Date());
		int result = tMaterielMapper.insert(tMateriel);
		if (result > 0) {
			TLog log = new TLog();
			log.setDataId(tMateriel.getId());
			log.setTableName(tableName);
			log.setOperationUser(getCurrentUser().getRealname());
			log.setOperationType(1);
			log.setCreateTime(new Date());
			tLogMapper.insertSelective(log);// 增加日记
		}
		return result;
	}

	@Override
	@Transactional
	public int updateMateriel(TMateriel tMateriel) throws Exception{
		// 通过id查询此物料
		TMateriel materiel = tMaterielMapper.selectByPrimaryKey(tMateriel.getId());
		materiel.setMaterielName(tMateriel.getMaterielName());
		materiel.setMaterielNo(tMateriel.getMaterielNo());
		materiel.setMaterielVolume(tMateriel.getMaterielVolume());
		materiel.setUpdateTime(new Date());
		// 修改物料
		int result = tMaterielMapper.updateByPrimaryKeySelective(materiel);
		if (result > 0) {
			TLog log = new TLog();
			log.setDataId(materiel.getId());
			log.setTableName(tableName);
			log.setOperationUser(getCurrentUser().getRealname());
			log.setOperationType(2);
			log.setCreateTime(new Date());
			tLogMapper.insertSelective(log);// 增加日记
		}
		return result;
	}

	@Override
	@Transactional
	public int deleteMaterielById(Long id) throws Exception{
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		int result = tMaterielMapper.deleteByPrimaryKey(id);
		if (result > 0) {
			TLog log = new TLog();
			log.setDataId(id);
			log.setTableName(tableName);
			log.setOperationUser(getCurrentUser().getRealname());
			log.setOperationType(3);
			log.setCreateTime(new Date());
			tLogMapper.insertSelective(log);// 增加日记
		}
		return result;
	}

	@Override
	public List<TMateriel> getMaterleiByIdOrCode(Long id, String name) throws Exception{
		Map<String, Object> map = new HashMap<>();
		if (id != null) {
			map.put("materielId", id);
		}
		if(StringUtils.isBlank(name)){
            throw new RuntimeException("数据不能空！");
        }
		map.put("materielNo", name);
		return materielExtendMapper.getMaterleiByIdOrCode(map);
	}

	@Override
	@Transactional
	public ExcelObjModel insertList(List<PageData> list) throws Exception {
		ExcelObjModel model = new ExcelObjModel();
		List<Object> mapList = new ArrayList<>();
		model.setCode(0); // 0没添加1添加成功，否则有添加不成功的
		int result = 0;
		Date now = new Date();
		// 遍历读取的Excel数据，判断数据的正确性
		for (PageData pd : list) {
			try {
				TMateriel tMateriel = new TMateriel();
				// 物料编码
				String materielNo = pd.getString("var0");
				tMateriel.setMaterielNo(materielNo);
				// 物料名称
				String materielName = pd.getString("var1");
				tMateriel.setMaterielName(materielName);
				// 物料体积
				String materielVolume = pd.getString("var2");
				if (StringUtils.isNoneBlank(materielVolume)) {
					tMateriel.setMaterielVolume(new BigDecimal(materielVolume));
				}
				// 将对象转化为map，判断是否为空
				Map<String, Object> map = com.chinawayltd.ews.sample.util.MapUtils.objectToMap(tMateriel);
				if (StringUtils.isBlank(materielNo) || StringUtils.isBlank(materielName)
						|| StringUtils.isBlank(materielVolume)) {
					map.put("describe", "填写的字段不能为空");
					mapList.add(map);
					continue;
				}
				tMateriel.setCreateTime(now);
				tMateriel.setUpdateTime(now);
				// TODO 查询物料编码是否重复
				// 判断编码的唯一性
				Map<String, Object> flag = judgeMaterielNoExist(tMateriel);
				if(MapUtils.getInteger(flag, "result") == 1){
					map.put("describe", "导入成功");
					mapList.add(map);
				}else if(MapUtils.getInteger(flag, "result") == 2){
					map.put("describe", "已更新");
					mapList.add(map);
				}else{
					map.put("describe", "导入异常");
					mapList.add(map);
					continue;
				}
				model.setCode(result);
			} catch (Exception e) {
				e.printStackTrace();
				model.setCode(0);
				Map<String, Object> exceptionMap = new HashMap<>();
				exceptionMap.put("materielNo", pd.getString("var0"));
				exceptionMap.put("materielName", pd.getString("var1"));
				exceptionMap.put("materielVolume", pd.getString("var2"));
				exceptionMap.put("describe", "数据异常，导入失败");
				mapList.add(exceptionMap);
			}
			
		}
		model.setList(mapList);
		List<ExportCloumsModel> cloums = new ArrayList<>();
		if(mapList.size() > 0){
			cloums.add(new ExportCloumsModel("物料编码", "materielNo"));
			cloums.add(new ExportCloumsModel("物料名称", "materielName"));
			cloums.add(new ExportCloumsModel("物料体积", "materielVolume"));
			cloums.add(new ExportCloumsModel("导入描述", "describe"));
		}
		model.setCloums(cloums);
		return model;
	}

	/**
	 * 判断物料编码唯一性
	 * 
	 * @author Fay
	 * @date 2018年5月3日 下午5:30:38
	 * @param tMateriel.getMaterielNo()
	 * @return
	 */
	@Transactional
	private Map<String, Object> judgeMaterielNoExist(TMateriel tMateriel) throws Exception{
		Map<String, Object> resultModel = new HashMap<>();
		int result = 0;
		TLog log = new TLog();
		
		TMaterielExample example = new TMaterielExample();
		example.createCriteria().andMaterielNoEqualTo(tMateriel.getMaterielNo());
		List<TMateriel> materielList = tMaterielMapper.selectByExample(example);
		if (materielList.size() > 0) {
			// 如果存在 就是不唯一 更新
			Long id = materielList.get(0).getId();
			tMateriel.setId(id);
			result = tMaterielMapper.updateByPrimaryKey(tMateriel);
			log.setOperationType(2);
			resultModel.put("result", 2);
		} else {
			// 如果不存在
			result = materielExtendMapper.insert(tMateriel);
			log.setOperationType(1);
			resultModel.put("result", result);
		}
		
		if(result > 0){
    		log.setDataId(tMateriel.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setCreateTime(new Date());
    		log.setUpdateTime(new Date());
    		tLogMapper.insert(log);
		}
		
		return resultModel;
	}

	@Override
	public List<Map<String, Object>> exportGirdData(MaterielGirdQuery queryParam) throws Exception{
		return materielExtendMapper.listMaterielToMap(queryParam);
	}
}
